import 'package:flutter/material.dart';
import 'package:hive/hive.dart';

part 'theme_config.g.dart';

/// 主题配置数据模型类
/// 定义应用的主题颜色和样式配置
@HiveType(typeId: 6)
class ThemeConfig {
  /// 主题配置ID
  @HiveField(0)
  final String id;

  /// 主题名称
  @HiveField(1)
  final String themeName;

  /// 主色调
  @HiveField(2)
  final String primaryColor;

  /// 强调色
  @HiveField(3)
  final String accentColor;

  /// 背景色
  @HiveField(4)
  final String backgroundColor;

  /// 表面色
  @HiveField(5)
  final String surfaceColor;

  /// 是否为深色主题
  @HiveField(6)
  final bool isDark;

  /// 创建时间
  @HiveField(7)
  final DateTime createdAt;

  /// 构造函数
  ThemeConfig({
    required this.id,
    required this.themeName,
    required this.primaryColor,
    required this.accentColor,
    required this.backgroundColor,
    required this.surfaceColor,
    required this.isDark,
    required this.createdAt,
  });

  /// 创建科技暗色主题
  factory ThemeConfig.techDark() {
    return ThemeConfig(
      id: 'tech_dark',
      themeName: '科技暗色',
      primaryColor: '#6C5CE7',
      accentColor: '#A29BFE',
      backgroundColor: '#0A0E27',
      surfaceColor: '#1E1E2E',
      isDark: true,
      createdAt: DateTime.now(),
    );
  }

  /// 创建科技亮色主题
  factory ThemeConfig.techLight() {
    return ThemeConfig(
      id: 'tech_light',
      themeName: '科技亮色',
      primaryColor: '#6C5CE7',
      accentColor: '#A29BFE',
      backgroundColor: '#FFFFFF',
      surfaceColor: '#F8F9FA',
      isDark: false,
      createdAt: DateTime.now(),
    );
  }

  /// 从JSON创建ThemeConfig对象
  factory ThemeConfig.fromJson(Map<String, dynamic> json) {
    return ThemeConfig(
      id: json['id'] as String,
      themeName: json['theme_name'] as String,
      primaryColor: json['primary_color'] as String,
      accentColor: json['accent_color'] as String,
      backgroundColor: json['background_color'] as String,
      surfaceColor: json['surface_color'] as String,
      isDark: json['is_dark'] is int 
          ? (json['is_dark'] as int) == 1 
          : json['is_dark'] as bool, // 处理int和bool两种格式
      createdAt: DateTime.fromMillisecondsSinceEpoch(json['created_at'] as int),
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'theme_name': themeName,
      'primary_color': primaryColor,
      'accent_color': accentColor,
      'background_color': backgroundColor,
      'surface_color': surfaceColor,
      'is_dark': isDark ? 1 : 0, // 将bool转换为int
      'created_at': createdAt.millisecondsSinceEpoch,
    };
  }

  /// 复制并修改部分属性
  ThemeConfig copyWith({
    String? id,
    String? themeName,
    String? primaryColor,
    String? accentColor,
    String? backgroundColor,
    String? surfaceColor,
    bool? isDark,
    DateTime? createdAt,
  }) {
    return ThemeConfig(
      id: id ?? this.id,
      themeName: themeName ?? this.themeName,
      primaryColor: primaryColor ?? this.primaryColor,
      accentColor: accentColor ?? this.accentColor,
      backgroundColor: backgroundColor ?? this.backgroundColor,
      surfaceColor: surfaceColor ?? this.surfaceColor,
      isDark: isDark ?? this.isDark,
      createdAt: createdAt ?? this.createdAt,
    );
  }

  /// 将十六进制颜色字符串转换为Color对象
  Color _hexToColor(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  /// 获取主色调Color对象
  Color get primaryColorValue => _hexToColor(primaryColor);

  /// 获取强调色Color对象
  Color get accentColorValue => _hexToColor(accentColor);

  /// 获取背景色Color对象
  Color get backgroundColorValue => _hexToColor(backgroundColor);

  /// 获取表面色Color对象
  Color get surfaceColorValue => _hexToColor(surfaceColor);

  /// 生成Flutter ThemeData
  ThemeData toThemeData() {
    final colorScheme = isDark
        ? ColorScheme.dark(
            primary: primaryColorValue,
            secondary: accentColorValue,
            surface: surfaceColorValue,
          )
        : ColorScheme.light(
            primary: primaryColorValue,
            secondary: accentColorValue,
            surface: surfaceColorValue,
          );

    return ThemeData(
      useMaterial3: true,
      colorScheme: colorScheme,
      brightness: isDark ? Brightness.dark : Brightness.light,

      // AppBar主题
      appBarTheme: AppBarTheme(
        backgroundColor: surfaceColorValue,
        foregroundColor: isDark ? Colors.white : Colors.black,
        elevation: 0,
        centerTitle: true,
        titleTextStyle: TextStyle(
          fontSize: 20,
          fontWeight: FontWeight.bold,
          color: isDark ? Colors.white : Colors.black,
        ),
      ),

      // 卡片主题
      cardTheme: CardTheme(
        color: surfaceColorValue,
        elevation: 4,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
        ),
      ),

      // 按钮主题
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
          backgroundColor: primaryColorValue,
          foregroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
        ),
      ),

      // 文本主题
      textTheme: TextTheme(
        headlineLarge: TextStyle(
          fontSize: 24,
          fontWeight: FontWeight.bold,
          color: isDark ? Colors.white : Colors.black,
        ),
        headlineMedium: TextStyle(
          fontSize: 20,
          fontWeight: FontWeight.w600,
          color: isDark ? Colors.white : Colors.black,
        ),
        bodyLarge: TextStyle(
          fontSize: 16,
          color: isDark ? Colors.white70 : Colors.black87,
        ),
        bodyMedium: TextStyle(
          fontSize: 14,
          color: isDark ? Colors.white60 : Colors.black54,
        ),
      ),

      // 图标主题
      iconTheme: IconThemeData(
        color: isDark ? Colors.white70 : Colors.black54,
        size: 24,
      ),

      // 滑块主题
      sliderTheme: SliderThemeData(
        activeTrackColor: primaryColorValue,
        inactiveTrackColor: primaryColorValue.withOpacity(0.3),
        thumbColor: primaryColorValue,
        overlayColor: primaryColorValue.withOpacity(0.2),
      ),

      // 进度指示器主题
      progressIndicatorTheme: ProgressIndicatorThemeData(
        color: primaryColorValue,
        linearTrackColor: primaryColorValue.withOpacity(0.3),
      ),
    );
  }

  /// 获取渐变色
  LinearGradient get primaryGradient {
    return LinearGradient(
      colors: [
        primaryColorValue,
        accentColorValue,
      ],
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
    );
  }

  /// 获取科技感光效颜色
  List<Color> get glowColors {
    return [
      primaryColorValue.withOpacity(0.8),
      accentColorValue.withOpacity(0.6),
      primaryColorValue.withOpacity(0.4),
    ];
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is ThemeConfig && other.id == id;
  }

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() {
    return 'ThemeConfig(id: $id, themeName: $themeName, isDark: $isDark)';
  }
}
